<?php

/* 
 * Copyright (c) 2009, Nguyen Duc Thuan <me@ndthuan.com>
 * All rights reserved.
 */

/**
 * Fete_View_Control_TagCloud
 *
 * Used to process tag cloud
 *
 * Example:
 * $tagCloud = new Fete_View_Control_TagCloud(array('tagOne' => 4, 'tagTwo' => 1));
 * $tagCloud->setMinSize(10)->setMaxSize(100)->sortByTagName()->renderAsHtml();
 */
class Fete_View_Control_TagCloud
{
    protected $_tags        = array();
    protected $_minSize     = 8;
    protected $_maxSize     = 50;

    public function __construct($tags = array())
    {
        $this->_tags = $tags;
    }

    /**
     *
     * @return Fete_View_Control_TagCloud
     */
    public function &sortByTagName()
    {
        ksort($this->_tags, SORT_STRING);

        return $this;
    }

    /**
     *
     * @return Fete_View_Control_TagCloud
     */
    public function &sortByCount()
    {
        asort($this->_tags, SORT_NUMERIC);

        return $this;
    }

    /**
     *
     * @param string $tag
     * @param integegr $count
     * @return Fete_View_Control_TagCloud
     */
    public function &setTag($tag, $count)
    {
        $this->_tags[$tag] = $count;

        return $this;
    }

    /**
     *
     * @param integer $num
     * @return Fete_View_Control_TagCloud
     */
    public function &setMinSize($num)
    {
        $this->_minSize = $num;

        return $this;
    }

    /**
     *
     * @param integer $num
     * @return Fete_View_Control_TagCloud
     */
    public function &setMaxSize($num)
    {
        $this->_maxSize = $num;

        return $this;
    }

    /**
     *
     * @return array
     */
    public function getTags()
    {
        return $this->_tags;
    }

    /**
     *
     * @return array
     */
    public function getTagsWithSize()
    {
        $tags       = array();
        $minCount   = 0;
        $maxCount   = 0;

        foreach ($this->_tags as $tag => $count)
        {
            if ($count < $minCount) {
                $minCount = $count;
            }

            if ($count > $maxCount) {
                $maxCount = $count;
            }
        }

        $countRange     = $maxCount - $minCount;
        $pixelsRange    = $this->_maxSize - $this->_minSize;
        $pixelsPerCount = $countRange < 1 ? 0 : round($pixelsRange/$countRange, 1);

        foreach ($this->_tags as $tag => $count)
        {
            $tags[$tag] = $count*$pixelsPerCount + $this->_minSize;
        }

        return $tags;
    }

    /**
     *
     * @return Fete_View_Control_TagCloud
     */
    public function &renderAsHtml()
    {
        foreach ($this->getTagsWithSize() as $tag => $size)
        {
            echo '<span style="font-size:' . $size . 'px">' . $tag . '</span> ';
        }

        return $this;
    }

    public function __toString()
    {
        ob_start();
        $this->renderAsHtml();
        return ob_get_clean();
    }
}